/* eslint-disable no-unused-vars,no-undef */
import axios from 'axios';
import { message } from 'antd';
import { base64encode } from 'Util/Base64';
import {clearToken,getToken} from 'Util/loginUtil';

var getRandomColor = function () {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

function parseErrorMessage(data) {
  const { status, message } = data;
  if (status === 'error') {
    message.error(message || '未知错误');
  }
  return data;
}

const axiosRequest = (options, consoleStyle) => {
  let { method, url, data } = options;
  data = data || {};
  let headers = {};
  if (url !== "Login") {
    headers = {
      Authorization: "Basic " + base64encode(getToken())
    }
  }

  const _baseURL = url.indexOf('http') === 0 ? '' : baseURL;

  // console.log('%c url:', consoleStyle, _baseURL + url);
  // console.log('%c params:', consoleStyle, data);
  const instance = axios.create({
    baseURL: _baseURL,
    timeout: 30000,
    headers,
    paramsSerializer(params) {

    },
    // withCredentials: true,
  });
  switch (method.toLowerCase()) {
    case 'get':
      return instance.get(url, {
        params: JSON.stringify(data),
      });
    case 'delete':
      return instance.delete(url, {
        data,
      });
    case 'post':
      return instance.post(url, data);
    case 'put':
      return instance.put(url, data);
    case 'patch':
      return instance.patch(url, data);
    default:
      return instance(options);
  }
};

export default function request(options) {
  const consoleStyle = 'background:' + getRandomColor() + ';font-weight:bold;font-size:15px;';
  return axiosRequest(options, consoleStyle)
    .then((response) => {
      const { statusText, status, header } = response;
      // console.log('%c response:', consoleStyle, response);
      // const token = header.access-token;
      // if (token) {
      //   sessionStorage.setItem('access_token', token);
      // }
      if (response.data.Result === 0) {
        return response.data.Info || {};
      } else {
        const messageStr = response.data.Msg;
        handleError(messageStr);
      }
    })
    .catch((error) => {
      const { response } = error;
      let messageStr;
      if (response) {
        const { status, header } = response;
        if (status === 401 || status === 0) {
          messageStr = '授权失败';
					clearToken();
					window.location.href="#/Login";
        } else if (status === 404) {
          messageStr = '地址错误';
        } else {
          messageStr = 'status:' + status;
        }
      } else {
        messageStr = error.message;
        if (messageStr === "Network Error") {
          messageStr = '网络异常';
        }
      }
      handleError(messageStr);
      // throw new Error(messageStr);
    });
}

//错误处理
const handleError = (msg) => {
  message.error(msg || '未知错误');
}
